import {
  Injectable,
  InternalServerErrorException,
  BadRequestException,
} from '@nestjs/common';
import { CreateAnFileDto } from './dto/create-an-file.dto';
import { UpdateAnFileDto } from './dto/update-an-file.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AnFile } from './entities/an-file.entity';
import { FastDFSService } from 'src/common/core/fastdfs/fastdfs.service';

@Injectable()
export class AnFileService {
  constructor(
    @InjectRepository(AnFile)
    private AnFileRepository: Repository<AnFile>,

    private readonly fastDFSservice: FastDFSService,
  ) {}

  // 新增
  async create(file: any, createAnFileDto: CreateAnFileDto) {
    const { originalname, size } = file;
    const anfileDate: CreateAnFileDto = Object.assign({}, createAnFileDto);
    // 调用FastDFS服务上传文件
    const fileId = await this.fastDFSservice.uploadFile(file);
    anfileDate.name = originalname;
    anfileDate.path = fileId;
    anfileDate.size = size;

    try {
      return await this.AnFileRepository.save(anfileDate);
    } catch (e) {
      throw new InternalServerErrorException('参数错误！');
    }
  }

  // 查询列表
  async findAll(query: any) {
    const { startTime, endTime, page = 1, pageSize = 10 } = query;

    let qb = this.AnFileRepository.createQueryBuilder('anFile');

    if (startTime && endTime) {
      const parsedStartDate = new Date(startTime);
      const parsedEndDate = new Date(endTime);
      if (isNaN(parsedStartDate.getTime()) || isNaN(parsedEndDate.getTime())) {
        throw new BadRequestException('时间格式错误');
      }
      qb = qb.where(
        'anFile.createdTime BETWEEN :parsedStartDate AND :parsedEndDate',
        {
          parsedStartDate,
          parsedEndDate,
        },
      );
    }

    qb = qb.skip((page - 1) * pageSize).take(pageSize);
    const [items, totalItemsCount] = await qb.getManyAndCount();
    return {
      total: totalItemsCount,
      data: items,
    };
  }

  findOne(id: string) {
    return this.AnFileRepository.findOneBy({ id: id });
  }

  update(id: string, updateAnFileDto: UpdateAnFileDto) {
    return this.AnFileRepository.update(id, updateAnFileDto);
  }

  // 批量删除
  remove(ids: string[]) {
    ids.forEach(async (id) => {
      const fileDate = await this.findOne(id);
      this.fastDFSservice.deleteFile(fileDate.path);
    });
    return this.AnFileRepository.delete(ids);
  }
}
